package com.lych.dubbo.api;

import com.lych.dubbo.utils.IdWorker;
import com.lych.model.mongo.Video;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 视频上传
     * @param video
     */
    @Override
    public Video save(Video video) {
        video.setVid(idWorker.getNextId("video"));
        video.setId(ObjectId.get());
        Video save = mongoTemplate.save(video);
        return save;
    }

    /**
     * 查询视频数据并分页
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Video> findAll(Integer page, Integer pagesize) {
        Query query = new Query().skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }

    /**
     * 根据id查询视频并分页
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    @Override
    public List<Video> findByUserId(Integer page, Integer pagesize, Long uid) {
        Query query = Query.query(Criteria.where("userId").is(uid))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }

    /**
     * 进行视频点赞
     * @param id
     */
    @Override
    public void idLike(String id, Long userId) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(id))
                .and("userId").is(userId));
        Update update = new Update();
        update.inc("likeCount",1);
        mongoTemplate.updateFirst(query,update,Video.class);
    }

    /**
     * 取消视频点赞
     * @param id
     * @param userId
     */
    @Override
    public void dislike(String id, Long userId) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(id))
                .and("userId").is(userId));
        Update update = new Update();
        update.inc("likeCount",-1);
        mongoTemplate.updateFirst(query,update,Video.class);
    }


}
